package vip.aster.license.controller;

import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.aster.common.utils.ResultInfo;
import vip.aster.license.core.LicenseCreator;
import vip.aster.license.core.LicenseCreatorParam;

/**
 * 用于生成证书文件，不能放在给客户部署的代码里
 *
 * @author Aster
 */
@RestController
@RequestMapping("/license")
public class LicenseCreatorController {
    /** 证书subject */
    private static final String SUBJECT = "aster-license";
    /** 访问公钥库的密码 */
    private static final String STORE_PASS = "aster.vip@2025";
    /** 生成证书后存放的路径 */
    private static final String LICENSE_PATH = "D://license//license.lic";
    /** 私钥路径 */
    private static final String PRIVATE_KEYS_STORE_PATH = "D://license//privateKeys.keystore";
    /** 私钥密码 */
    private static final String KEY_PASS = "aster.vip@2025";
    /** 私钥别称 */
    private static final String PRIVATE_ALIAS = "privateKey";

    /**
     * 生成证书
     *
     * @param param 生成证书需要的参数，如：{"subject":"ccx-models","privateAlias":"privateKey","keyPass":"5T7Zz5Y0dJFcqTxvzkH5LDGJJSGMzQ","storePass":"3538cef8e7","licensePath":"C:/Users/zifangsky/Desktop/license.lic","privateKeysStorePath":"C:/Users/zifangsky/Desktop/privateKeys.keystore","issuedTime":"2018-04-26 14:48:12","expiryTime":"2018-12-31 00:00:00","consumerType":"User","consumerAmount":1,"description":"这是证书描述信息","licenseCheckModel":{"ipAddress":["192.168.245.1","10.0.5.22"],"macAddress":["00-50-56-C0-00-01","50-7B-9D-F9-18-41"],"cpuSerial":"BFEBFBFF000406E3","mainBoardSerial":"L1HF65E00X9"}}
     */
    @PostMapping("/generateLicense")
    public ResultInfo<String> generateLicense(@RequestBody LicenseCreatorParam param) {
        if (StrUtil.isBlank(param.getSubject())) {
            param.setSubject(SUBJECT);
        }
        if (StrUtil.isBlank(param.getStorePass())) {
            param.setStorePass(STORE_PASS);
        }
        if (StrUtil.isBlank(param.getLicensePath())) {
            param.setLicensePath(LICENSE_PATH);
        }
        if (StrUtil.isBlank(param.getPrivateKeysStorePath())) {
            param.setPrivateKeysStorePath(PRIVATE_KEYS_STORE_PATH);
        }
        if (StrUtil.isBlank(param.getKeyPass())) {
            param.setKeyPass(KEY_PASS);
        }
        if (StrUtil.isBlank(param.getPrivateAlias())) {
            param.setPrivateAlias(PRIVATE_ALIAS);
        }

        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();

        if (result) {
            return ResultInfo.success("证书生成成功！");

        } else {
            return ResultInfo.failed("证书文件生成失败！");
        }
    }

}
